package com.cloud.point.concurrent.general;

import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;

/**
 * 无锁并发--cas操作
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-21 12:13
 */
@Slf4j
public class TestCASLock {

    public static void main(String[] args) {
        LockAddr lockAddr = new LockAddr();

        new Thread(() -> {
            log.info("{}运行", Thread.currentThread().getName());
            lockAddr.lock();
            try {
                log.info("{}睡眠", Thread.currentThread().getName());
                Thread.sleep(2000);
                //TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lockAddr.unlock();
            }
        }, "t1").start();


        new Thread(() -> {
            log.info("{}运行", Thread.currentThread().getName());
            lockAddr.lock();
            try {
                log.info("{}睡眠", Thread.currentThread().getName());
                Thread.sleep(2000);
                //TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lockAddr.unlock();
            }
        }, "t2").start();

    }

    static class LockAddr {

        private static final AtomicInteger lock = new AtomicInteger(0);

        public void lock() {
            while (true) {
                log.info("{}竞争锁", Thread.currentThread().getName());
                if (lock.compareAndSet(0, 1)) {
                    log.info("{}加锁", Thread.currentThread().getName());
                    break;
                }
            }
        }

        public void unlock() {
            log.info("{}解锁", Thread.currentThread().getName());
            lock.set(0);
        }

    }

}
